package com.tenda.sonicdemo;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;

import com.tencent.sonic.sdk.SonicCacheInterceptor;
import com.tencent.sonic.sdk.SonicConfig;
import com.tencent.sonic.sdk.SonicConstants;
import com.tencent.sonic.sdk.SonicEngine;
import com.tencent.sonic.sdk.SonicSession;
import com.tencent.sonic.sdk.SonicSessionConfig;
import com.tencent.sonic.sdk.SonicSessionConnection;
import com.tencent.sonic.sdk.SonicSessionConnectionInterceptor;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    private WebView mWebView;
    private Button btnRefresh;
    //    private String htmlUrl = "http://192.168.10.66:8080/zgbH5/help.html?&token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpdyI6IlRodSBBdWcgMTcgMTE6Mzg6MDMgQ1NUIDIwMTcifQ.S6k9z8-p_qBEw0HlCHTNbaU8JA64Y2up16OpBQMYWF8userId:678";
    private String htmlUrl = "file:///android_asset/zgbHtml/help.html?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpdyI6IlRodSBBdWcgMjQgMTQ6NDI6MjAgQ1NUIDIwMTcifQ.qgkCewEnn9AlGbW5TzIOCVCy-1vVK_xV_QEdo6L7sjcuserId:678";
    private SonicSession mSonicSession;
    //

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int mode = getIntent().getIntExtra("mode", -1);

        htmlUrl=FileUtils.getHtmlPath(getApplicationContext(),"/help.html?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpdyI6IlRodSBBdWcgMjQgMTQ6NDI6MjAgQ1NUIDIwMTcifQ.qgkCewEnn9AlGbW5TzIOCVCy-1vVK_xV_QEdo6L7sjcuserId:678");
        Log.e("htmlUrl--->",htmlUrl);
        if (!SonicEngine.isGetInstanceAllowed()) {
            SonicEngine.createInstance(new MySonicRuntimeImpl(getApplication()), new SonicConfig.Builder().build());
        }

        MySonicSessionClientImpl mySonicSessionClient = null;

        SonicSessionConfig.Builder sessionConfigBuilder = new SonicSessionConfig.Builder();

        //离线方式加载
        if (mode == 2) {
            sessionConfigBuilder.setCacheInterceptor(new SonicCacheInterceptor(null) {
                @Override
                public String getCacheData(SonicSession session) {
                    return null;
                }
            });

            sessionConfigBuilder.setConnectionIntercepter(new SonicSessionConnectionInterceptor() {
                @Override
                public SonicSessionConnection getConnection(SonicSession session, Intent intent) {
                    return new OffLineSessionConnection(MainActivity.this, session, intent);
                }
            });
        }


        mSonicSession = SonicEngine.getInstance().createSession(htmlUrl, sessionConfigBuilder.build());
        if (mSonicSession != null) {
            mSonicSession.bindClient(mySonicSessionClient = new MySonicSessionClientImpl());
        } else {
            throw new UnknownError("create session fail!");
        }

        setContentView(R.layout.activity_main);
        btnRefresh = (Button) findViewById(R.id.btn_refresh);
        btnRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String jsCode = "javascript:" + "vm.getData" + "('" +
                        "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpdyI6IlRodSBBdWcgMjQgMTA6NDY6MDUgQ1NUIDIwMTcifQ.szx0SkNTnBQVUjxsvJ31SuwalcLq_9ZbLix5a2UZHTQuserId:677" + "')";
                mWebView.loadUrl(jsCode);

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        FileUtils.copyAssetsToSDCard(getApplicationContext(),"zgbHtml", Environment.getExternalStorageDirectory().getAbsolutePath()+"/zgbHtml");
                    }
                }).start();
            }
        });

        mWebView = (WebView) findViewById(R.id.webView);

        mWebView.setWebViewClient(new WebViewClient() {

            @Override
            @TargetApi(21)
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                return shouldOverrideUrlLoading(view, request.getUrl().toString());
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.e("UrlLoading--->", url);
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (mSonicSession != null) {
                    mSonicSession.getSessionClient().pageFinish(url);
                }
            }

            @Override
            @TargetApi(21)
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                Map<String, String> headers = request.getRequestHeaders();
                String token = headers.get("token");
                Log.e("loadUrlToken--->", request.getUrl().toString() + "   token=" + token);
                return shouldInterceptRequest(view, request.getUrl().toString());
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                Uri uri = Uri.parse(url);
                if (url.contains("getContent")) {
                    String id = uri.getQueryParameter("id");
                    String title = uri.getQueryParameter("title");
                    String token = uri.getQueryParameter("token");
                    Log.e("loadUrl--->", "id=" + id + "  title=" + title + "  token=" + token);
                }
                Log.e("loadUrl--->", url);
                if (mSonicSession != null) {
                    return (WebResourceResponse) mSonicSession.getSessionClient().requestResource(url);
                }
                return null;
            }
        });

        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        mWebView.removeJavascriptInterface("searchBoxJavaBridge_");
        mWebView.addJavascriptInterface(new MyJavaScriptInterface(mySonicSessionClient), "sonic");

        webSettings.setAllowContentAccess(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setSaveFormData(false);
        webSettings.setSavePassword(false);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);

        if (mySonicSessionClient != null) {
            mySonicSessionClient.bindWebView(mWebView);
            mySonicSessionClient.clientReady();
        } else {
            mWebView.loadUrl(htmlUrl);
        }
    }


    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
        }
        super.onBackPressed();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        if (mSonicSession != null) {
            mSonicSession.destroy();
            mSonicSession = null;
        }
        super.onDestroy();
    }

    public static class OffLineSessionConnection extends SonicSessionConnection {

        private final WeakReference<Context> mContextWeakReference;

        /**
         * Constructor
         *
         * @param session The SonicSession instance
         * @param intent  The intent
         */
        public OffLineSessionConnection(Context context, SonicSession session, Intent intent) {
            super(session, intent);
            mContextWeakReference = new WeakReference<>(context);
        }

        @Override
        public void disconnect() {
            if (responseStream != null) {
                try {
                    responseStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public int getResponseCode() {
            return 200;
        }

        @Override
        public Map<String, List<String>> getResponseHeaderFields() {
            return new HashMap<>(0);
        }

        @Override
        public String getResponseHeaderField(String key) {
            return "";
        }

        @Override
        protected int internalConnect() {
            Context context = mContextWeakReference.get();
            if (context != null) {
                try {
                    InputStream inputStream = context.getAssets().open("zgbHtml/help.html");
                    responseStream = new BufferedInputStream(inputStream);
                    return SonicConstants.ERROR_CODE_SUCCESS;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return SonicConstants.ERROR_CODE_UNKNOWN;
        }

        @Override
        protected BufferedInputStream internalGetResponseStream() {
            return responseStream;
        }
    }
}
